package cn.enjoy.dynamic.datasource.utils;

import cn.enjoy.dynamic.datasource.config.DynamicDataSource;
import cn.enjoy.dynamic.datasource.config.DynamicDataSourceFactory;
import cn.enjoy.dynamic.datasource.prop.DataSourceProperties;
import cn.enjoy.tool.utils.SpringUtil;
import com.alibaba.druid.pool.DruidDataSource;

import java.util.HashMap;
import java.util.Map;

/**
 * dataSourceMap 存储数据源信息
 *
 * @author K
 * @date 2020/12/14 20:14
 */
public class DataSourceUtil {

    public static Map<Object, Object> dataSourceMap = new HashMap<>(16);

    /**
     * 添加数据源
     *
     * @param name                 名称
     * @param dataSourceProperties 配置
     */
    public static boolean addDataSource(String name, DataSourceProperties dataSourceProperties) {
        if (dataSourceMap.containsKey(name)) {
            return false;
        }
        DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties);
        dataSourceMap.put(name, druidDataSource);
        return true;
    }

    /**
     * 批量添加数据源
     */
    public static void addDataSourceBatch(Map<String, DataSourceProperties> dataSourcePropertiesMap) {
        dataSourcePropertiesMap.forEach(DataSourceUtil::addDataSource);
    }

    /**
     * 刷新数据源
     */
    public static void flushDataSource() {
        DynamicDataSource dynamicDataSource = SpringUtil.getBean(DynamicDataSource.class);
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        //将 targetDataSources 中的连接信息放入 resolvedDataSources 管理
        dynamicDataSource.afterPropertiesSet();
    }

}
